﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Text;
using System.Data;
using DevExpress.Web.ASPxGridView;
using GPSTracker.Views.DAL;
using GPSTracker.Helper;
using System.Xml;
using DevExpress.Web.ASPxEditors;
using System.Data.SqlClient;

namespace GPSTracker.Views.Master
{
    public partial class Login : System.Web.UI.Page
    {
        private LoginDAL objLoginDAL = new LoginDAL();
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                var objLoginDAL = new LoginDAL();
                if (!IsPostBack)
                {
                    BindDesignation(string.Empty);
                    BindBranch(string.Empty);
                    BindWarehouse(string.Empty);
                }
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Login Profile", "Page_Load");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        public void BindGridview()
        {
            try
            {
                grdView.DataBind();
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Login Profile", "BindGridview");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        public void BindDesignation(string strDesignationID)
        {
            try
            {
                var objLoginDAL = new LoginDAL();
                var dt = new DataTable();
                if (strDesignationID == string.Empty)
                {
                    dt = objLoginDAL.FillDesignation(string.Empty);
                }
                else
                {
                    dt = objLoginDAL.FillDesignation(strDesignationID);
                }
                if (dt.Rows.Count > 0)
                {
                    cmbDesignation.DataSource = dt;
                    cmbDesignation.TextField = "Name";
                    cmbDesignation.ValueField = "AttributeID";
                    cmbDesignation.DataBind();
                }
                else
                {
                }
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Login Profile", "BindDesignation");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        public void BindBranch(string strBranchID)
        {
            try
            {
                var objLoginDAL = new LoginDAL();
                var dt = new DataTable();
                if (strBranchID == string.Empty)
                {
                    dt = objLoginDAL.FillBranch(string.Empty);
                }
                else
                {
                    dt = objLoginDAL.FillBranch(strBranchID);
                }
                if (dt.Rows.Count > 0)
                {
                    cmbBranch.DataSource = dt;
                    cmbBranch.TextField = "BranchCode";
                    cmbBranch.ValueField = "BranchID";
                    cmbBranch.DataBind();
                }
                else
                {
                }
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Login Profile", "BindBranch");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        public void BindWarehouse(string strWareHouseID)
        {
            try
            {
                var objLoginDAL = new LoginDAL();
                var dt = new DataTable();
                if (strWareHouseID == string.Empty)
                {
                    dt = objLoginDAL.FillWarehouse(string.Empty);
                }
                else
                {
                    dt = objLoginDAL.FillWarehouse(strWareHouseID);
                }
                if (dt.Rows.Count > 0)
                {
                    cmbWarehouse.DataSource = dt;
                    cmbWarehouse.TextField = "WhouseNo";
                    cmbWarehouse.ValueField = "WhouseID";
                    cmbWarehouse.DataBind();
                }
                else
                {
                }
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Login Profile", "BindWarehouse");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        protected void cmbDesignation_Init(object sender, EventArgs e)
        {
            if ((sender as ASPxComboBox).Value == null)
            {
                (sender as ASPxComboBox).Text = "--Select--";
            }
        }

        protected void cmb_DataBound(object sender, EventArgs e)
        {
            var list = sender as ASPxComboBox;
            var lEi = new ListEditItem();
            lEi.Text = "--Select--";
            if (list != null)
            {
                list.Items.Insert(0, lEi);
            }
            list.SelectedIndex = 0;
        }

        protected void grdView_CustomButtonCallback(object sender, ASPxGridViewCustomButtonCallbackEventArgs e)
        {
            try
            {
                var grid = (ASPxGridView)sender;
                var keyValue = grid.GetRowValues(e.VisibleIndex, "LoginID").ToString();
                hdnLoginID.Value = keyValue;

                if (e.ButtonID == "btnEdit")
                {
                    txtLoginName.Focus();
                    btnUpdate.Visible = true;
                    btnSave.Visible = false;
                    lblMessage.Visible = false;
                    lblMessage.Text = string.Empty;
                    ClearPopUpCntrls(true, false);
                    popup.ShowOnPageLoad = true;

                    var dt = new DataTable();
                    dt = objLoginDAL.FillLoginMasterGrid(keyValue);
                    if (dt.Rows.Count > 0)
                    {
                        txtLoginName.Text = dt.Rows[0]["LoginName"].ToString();
                        txtPassword.Text = dt.Rows[0]["Password"].ToString();
                        txtFirstName.Text = dt.Rows[0]["FirstName"].ToString();
                        txtMiddleName.Text = dt.Rows[0]["MiddleName"].ToString();
                        txtLastName.Text = dt.Rows[0]["LastName"].ToString();
                        txtDisplayName.Text = dt.Rows[0]["DisplayName"].ToString();
                        txtMobileNo1.Text = dt.Rows[0]["MobileNo1"].ToString();
                        txtMobileNo2.Text = dt.Rows[0]["MobileNo2"].ToString();
                        txtAdharCardNo.Text = dt.Rows[0]["AdharCardNo"].ToString();
                        txtDrivingLicenseNo.Text = dt.Rows[0]["DrivingLicenseNo"].ToString();
                        txtPanCardNo.Text = dt.Rows[0]["PanCardNo"].ToString();
                        txtResidenceAddress.Text = dt.Rows[0]["ResidenceAddress"].ToString();
                        txtEmailID.Text = dt.Rows[0]["EmailID"].ToString();

                        var strDesignationID = dt.Rows[0]["DesignationID"].ToString();
                        if (strDesignationID != string.Empty)
                        {
                            BindDesignation(strDesignationID);
                            cmbDesignation.Value = strDesignationID;
                        }
                        else
                        {
                            BindDesignation(string.Empty);
                        }

                        var strBranchID = dt.Rows[0]["BranchID"].ToString();
                        if (strBranchID != string.Empty)
                        {
                            BindBranch(strBranchID);
                            cmbBranch.Value = strBranchID;
                        }
                        else
                        {
                            BindBranch(string.Empty);
                        }

                        var strWareHouseID = dt.Rows[0]["WarehouseID"].ToString();
                        if (strWareHouseID != string.Empty)
                        {
                            BindWarehouse(strWareHouseID);
                            cmbWarehouse.Value = strWareHouseID;
                        }
                        else
                        {
                            BindWarehouse(string.Empty);
                        }

                        if (dt.Rows[0]["IsAdmin"].ToString().ToUpper() == "YES")
                        {
                            chkIsAdmin.Checked = true;
                        }
                        else
                        {
                            chkIsAdmin.Checked = false;
                        }

                        if (dt.Rows[0]["IsBlock"].ToString().ToUpper() == "YES")
                        {
                            chkIsBlock.Checked = true;
                        }
                        else
                        {
                            chkIsBlock.Checked = false;
                        }

                        if (dt.Rows[0]["IsActive"].ToString().ToUpper() == "YES")
                        {
                            chkIsActive.Checked = true;
                        }
                        else
                        {
                            chkIsActive.Checked = false;
                        }
                        if (dt.Rows[0]["IsMobileUser"].ToString().ToUpper() == "YES")
                        {
                            chkIsMobileUser.Checked = true;
                        }
                        else
                        {
                            chkIsMobileUser.Checked = false;
                        }

                        if (dt.Rows[0]["IsWebUser"].ToString().ToUpper() == "YES")
                        {
                            chkIsWebUser.Checked = true;
                        }
                        else
                        {
                            chkIsWebUser.Checked = false;
                        }
                    }
                }
                else
                {
                    if (e.ButtonID == "btnDelete")
                    {
                        objLoginDAL.DeleteUserMaster(keyValue);
                        BindGridview();
                    }
                }
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Login Profile", "grdView_CustomButtonCallback");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            try
            {
                ClearPopUpCntrls(false, false);
                lblMessage.Visible = false;
                btnSave.Visible = true;
                btnUpdate.Visible = false;
                popup.ShowOnPageLoad = true;
                txtLoginName.Focus();
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Login Profile", "btnNew_Click");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                BindGridview();
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Login Profile", "btnRefresh_Click");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                SaveData(true);
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Login Profile", "btnUpdate_Click");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            SaveData(false);
        }

        public void ClearPopUpCntrls(bool IsEditMode, bool IsSaveEdit)
        {
            try
            {
                txtLoginName.Text = string.Empty;
                txtPassword.Text = string.Empty;
                txtFirstName.Text = string.Empty;
                txtMiddleName.Text = string.Empty;
                txtLastName.Text = string.Empty;
                txtDisplayName.Text = string.Empty;
                txtMobileNo1.Text = string.Empty;
                txtMobileNo2.Text = string.Empty;

                txtAdharCardNo.Text = string.Empty;
                txtDrivingLicenseNo.Text = string.Empty;
                txtPanCardNo.Text = string.Empty;
                txtResidenceAddress.Text = string.Empty;

                txtEmailID.Text = string.Empty;

                if (IsEditMode == false)
                {
                    cmbDesignation.Items.Clear();
                    cmbBranch.Items.Clear();
                    cmbWarehouse.Items.Clear();
                    BindDesignation(string.Empty);
                    BindBranch(string.Empty);
                    BindWarehouse(string.Empty);
                }

                chkIsAdmin.Checked = false;
                chkIsBlock.Checked = false;
                chkIsActive.Checked = false;
                chkIsMobileUser.Checked = false;
                chkIsWebUser.Checked = false;
                if (IsSaveEdit == false)
                {
                    lblMessage.Text = string.Empty;
                }
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Login Profile", "ClearPopUpCntrls");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
            }
        }

        private bool SaveData(bool IsModify)
        {
            var settings = new XmlWriterSettings();
            settings.NewLineHandling = NewLineHandling.Entitize;
            settings.Indent = true;
            settings.OmitXmlDeclaration = true;

            var sb = new StringBuilder();

            try
            {
                var CmdSave = new SqlCommand();
                CmdSave.Connection = CommonFx.GetSqlCon();
                CmdSave.CommandType = CommandType.StoredProcedure;
                CmdSave.CommandText = "SP_InsertLoginMaster";

                using (var xw = XmlWriter.Create(sb, settings))
                {
                    xw.WriteStartDocument();
                    xw.WriteStartElement("CS");
                    xw.WriteStartElement("LoginMaster");
                    if (IsModify == true)
                    {
                        xw.WriteElementString("LoginID", hdnLoginID.Value);
                    }
                    xw.WriteElementString("LoginName", txtLoginName.Text.Trim());
                    xw.WriteElementString("Password", txtPassword.Text.Trim());
                    xw.WriteElementString("FirstName", txtFirstName.Text.Trim());
                    xw.WriteElementString("MiddleName", txtMiddleName.Text.Trim());
                    xw.WriteElementString("LastName", txtLastName.Text.Trim());
                    if (txtDisplayName.Text.Trim() != string.Empty)
                    {
                        xw.WriteElementString("DisplayName", txtDisplayName.Text.Trim());
                    }
                    else
                    {
                        var strDisplayName = txtFirstName.Text.Trim() + " " + txtMiddleName.Text.Trim() + " " + txtLastName.Text.Trim();
                        xw.WriteElementString("DisplayName", strDisplayName);
                    }
                    if (cmbDesignation.Text != "--Select--" && cmbDesignation.Text != string.Empty)
                    {
                        xw.WriteElementString("DesignationID", cmbDesignation.Value.ToString());
                    }
                    else
                    {
                        xw.WriteElementString("DesignationID", "0");
                    }

                    xw.WriteElementString("MobileNo1", txtMobileNo1.Text.Trim());
                    xw.WriteElementString("MobileNo2", txtMobileNo2.Text.Trim());
                    xw.WriteElementString("AdharCardNo", txtAdharCardNo.Text.Trim());
                    xw.WriteElementString("DrivingLicenseNo", txtDrivingLicenseNo.Text.Trim());
                    xw.WriteElementString("Panno", txtPanCardNo.Text.Trim());
                    xw.WriteElementString("ResidenceAddress", txtResidenceAddress.Text.Trim());
                    
                    xw.WriteElementString("EmailID", txtEmailID.Text.Trim());
                    if (chkIsAdmin.Checked == true)
                    {
                        xw.WriteElementString("IsAdmin", "1");
                    }
                    else
                    {
                        xw.WriteElementString("IsAdmin", "0");
                    }
                    if (chkIsBlock.Checked == true)
                    {
                        xw.WriteElementString("IsBlock", "1");
                    }
                    else
                    {
                        xw.WriteElementString("IsBlock", "0");
                    }
                    if (chkIsActive.Checked == true)
                    {
                        xw.WriteElementString("IsActive", "1");
                    }
                    else
                    {
                        xw.WriteElementString("IsActive", "0");
                    }
                    if (chkIsMobileUser.Checked == true)
                    {
                        xw.WriteElementString("IsMobileUser", "1");
                    }
                    else
                    {
                        xw.WriteElementString("IsMobileUser", "0");
                    }
                    if (chkIsWebUser.Checked == true)
                    {
                        xw.WriteElementString("IsWebUser", "1");
                    }
                    else
                    {
                        xw.WriteElementString("IsWebUser", "0");
                    }
                    if (cmbBranch.Text != "--Select--" && cmbBranch.Text != string.Empty)
                    {
                        xw.WriteElementString("BranchID", cmbBranch.Value.ToString());
                    }
                    else
                    {
                        xw.WriteElementString("BranchID", "0");
                    }
                    if (cmbWarehouse.Text != "--Select--" && cmbWarehouse.Text != string.Empty)
                    {
                        xw.WriteElementString("WarehouseID", cmbWarehouse.Value.ToString());
                    }
                    else
                    {
                        xw.WriteElementString("WarehouseID", "0");
                    }
                    var lg = Session["LoginMaster"] as Views.DAL.LoginBO;
                    xw.WriteElementString("CreatedBy", lg.LoginID.ToString());
                    xw.WriteElementString("ModifiedBy", lg.LoginID.ToString());
                    xw.WriteEndElement();
                    xw.WriteEndDocument();
                    xw.Close();
                }
                CmdSave.Parameters.Add(new SqlParameter("@pXML", sb.ToString()));
                if (IsModify == false)
                {
                    CmdSave.Parameters.Add(new SqlParameter("@pIsUpdate", false));
                }
                else
                {
                    CmdSave.Parameters.Add(new SqlParameter("@pIsUpdate", true));
                }

                CmdSave.Parameters.Add("@pIsErrorFound", SqlDbType.Bit);
                CmdSave.Parameters.Add("@pErrorMessage", SqlDbType.NVarChar, 4000);
                CmdSave.Parameters.Add("@pLoginID", SqlDbType.Int);

                CmdSave.Parameters["@pIsErrorFound"].Direction = ParameterDirection.Output;
                CmdSave.Parameters["@pErrorMessage"].Direction = ParameterDirection.Output;
                CmdSave.Parameters["@pLoginID"].Direction = ParameterDirection.Output;

                CmdSave.ExecuteNonQuery();
                var strError = string.Empty;
                var str = CmdSave.Parameters["@pIsErrorFound"].Value.ToString();
                if (!Convert.ToBoolean(CmdSave.Parameters["@pIsErrorFound"].Value))
                {
                    if (IsModify == false)
                    {
                        strError = string.Empty;
                        lblMessage.Visible = true;
                        lblMessage.Text = "User Inserted Successfully.";
                        ScriptManager.RegisterStartupScript(UpMain, typeof(Page), "message", "Fade('" + lblMessage.ClientID + "');", true);
                        ClearPopUpCntrls(false, true);
                        txtLoginName.Focus();
                    }
                    else
                    {
                        strError = string.Empty;
                        lblMessage.Visible = true;
                        lblMessage.Text = "User Updated Successfully.";
                        ScriptManager.RegisterStartupScript(UpMain, typeof(Page), "message", "Fade('" + lblMessage.ClientID + "');", true);
                        txtLoginName.Focus();
                    }

                    return true;
                }
                else
                {
                    if (IsModify == false)
                    {
                        strError = CmdSave.Parameters["@pErrorMessage"].Value.ToString();
                        lblMessage.Visible = true;
                        lblMessage.Text = "Error Occured Kindly Contact Administrator.";
                    }
                    else
                    {
                        strError = CmdSave.Parameters["@pErrorMessage"].Value.ToString();
                        lblMessage.Visible = true;
                        lblMessage.Text = "Error Occured Kindly Contact Administrator.";
                    }
                    return false;
                }
            }
            catch (Exception ex)
            {
                CommonDAL.ErrorDAL.ErrorLog(ex.Message, "Login Profile", "SaveData");
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alertmessage", "javascript:alert('" + Helper.ExceptionHandler.GetErrorMsg(ex) + "');", true);
                return false;
            }
        }

        protected void ASPxCallbackDemo_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
        {
            System.Threading.Thread.Sleep(9000);
        }
    }
}
